package com.ice.interceptors;

import com.ice.utils.JwtUtil;
import com.ice.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //request  包含所有的请求信息，如token
        //获取token
        String token = request.getHeader("Authorization");
        //验证token
        try {
            //从redis中获取相网的token
            //获取redis操作
            ValueOperations operations = stringRedisTemplate.opsForValue();
            String redisToken = (String) operations.get(token);
            //token不纯在抛出异常
            if(redisToken == null){
                throw  new Exception();
            }
            Map<String ,Object> claims =  JwtUtil.parseToken(token);
           // 把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            //放行
            return  true;
        } catch (Exception e) {
            // 设置状态码
            response.setStatus(401);
            //不放行
            return false;
        }
    }
}
